// import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import router from '@/router'

let loadingInstance
/**
 * @author https://vue-admin-beautiful.com （不想保留author可删除）
 * @description 处理code异常
 * @param {*} code
 * @param {*} msg
 */
const handleCode = (code, msg) => {
  console.log(msg)
  switch (code) {
    //登录过期
    case 402:
      // Vue.prototype.$baseMessage(msg || `后端接口${code}异常`, 'error')
      store.dispatch('user/resetAccessToken').catch(() => { })
      location.reload()
      break
    //无权限
    case 401:
      router.push({ path: '/401' }).catch(() => { })
      break
    default:
      // Vue.prototype.$baseMessage(msg || `后端接口${code}异常`, 'error')
      break
  }
}

const instance = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:3000/api' : 'vab-mock-server',
  timeout: 5000,
  headers: {
    // contentType: 'application/json;charset=UTF-8',
    'Content-Type': 'application/json;charset=UTF-8',
  },
})

instance.interceptors.request.use(
  (config) => {
    if (store.getters['user/accessToken']) {
      config.headers['token'] = store.getters['user/accessToken']
    }
    //这里会过滤所有为空、0、false的key，如果不需要请自行注释
    // if (config.data) config.data = Vue.prototype.$baseLodash.pickBy(config.data, Vue.prototype.$baseLodash.identity)
    // if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8')
    //   config.data = qs.stringify(config.data)
    // if (debounce.some((item) => config.url.includes(item))) loadingInstance = Vue.prototype.$baseLoading()
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    if (loadingInstance) loadingInstance.close()
    console.log(response,'response')
    const { data, config } = response
    const { errno, msg } = data
    // 操作正常Code数组
    // const codeVerificationArray = isArray(successCode) ? [...successCode] : [...[successCode]]
    // 是否操作正常
    
    if (errno == 0) {
      return data
    } else {
      handleCode(errno, msg)
      return Promise.reject(
        `vue-admin-beautiful请求异常拦截:${JSON.stringify({
          url: config.url,
          errno,
          msg,
        })}` || 'Error'
      )
    }
  },
  (error) => {
    if (loadingInstance) loadingInstance.close()
    const { response, message } = error
    if (error.response && error.response.data) {
      const { status, data } = response
      handleCode(status, data.msg || message)
      return Promise.reject(error)
    } else {
      let { message } = error
      if (message === 'Network Error') {
        message = '后端接口连接异常'
      }
      if (message.includes('timeout')) {
        message = '后端接口请求超时'
      }
      if (message.includes('Request failed with status code')) {
        const code = message.substr(message.length - 3)
        message = `后端接口${code}异常`
      }
      // Vue.prototype.$baseMessage(message || `后端接口未知异常`, 'error')
      return Promise.reject(error)
    }
  }
)

export default instance